/**
 * 照护计划算法前端交互脚本
 * 用于处理表单提交和API调用
 */

// 当DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('照护计划算法前端已加载');
    
    // 设置日期输入框事件
    const dateInputs = document.querySelectorAll('input[type="date"]');
    dateInputs.forEach(input => {
        // 添加点击事件，确保在点击时显示日期选择器
        input.addEventListener('click', function() {
            this.showPicker();
        });
    });
});

/**
 * 下载特定老人的排班表
 */
function downloadSchedule() {
    const elderId = document.getElementById('elder-download').value;
    const date = document.getElementById('date-download').value;
    
    if (!elderId) {
        alert('请输入老人ID');
        return;
    }
    
    let url = `/download_schedule/${elderId}`;
    if (date && isValidDate(date)) {
        url += `?date=${date}`;
    }
    
    window.open(url, '_blank');
}

/**
 * 查看护理人员排班
 */
function viewCaregiverSchedule() {
    const caregiverId = document.getElementById('caregiver-id').value;
    const date = document.getElementById('caregiver-date').value;
    
    if (!caregiverId) {
        alert('请输入护理人员ID');
        return;
    }
    
    let url = `/caregiver_schedule/${caregiverId}`;
    if (date && isValidDate(date)) {
        url += `?date=${date}`;
    }
    
    window.open(url, '_blank');
}

/**
 * 更新护理人员可用性
 */
function updateAvailability() {
    const caregiverId = document.getElementById('update-caregiver-id').value;
    const date = document.getElementById('update-date').value;
    const timeSlot = document.getElementById('time-slot').value;
    const isAvailable = document.getElementById('is-available').value === 'true';
    const resultDiv = document.getElementById('update-result');
    
    if (!caregiverId || !date || timeSlot === '') {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证日期格式
    if (!isValidDate(date)) {
        alert('日期格式不正确，请使用YYYY-MM-DD格式');
        return;
    }
    
    // 准备请求数据
    const data = {
        caregiver_id: caregiverId,
        date: date,
        time_slot: parseInt(timeSlot),
        is_available: isAvailable
    };
    
    // 发送POST请求
    fetch('/update_caregiver_availability', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            resultDiv.className = 'error';
            resultDiv.textContent = `错误: ${data.error}`;
        } else {
            resultDiv.className = 'success';
            resultDiv.textContent = '更新成功!';
        }
    })
    .catch(error => {
        resultDiv.className = 'error';
        resultDiv.textContent = `请求失败: ${error.message}`;
    });
}

/**
 * 验证日期格式是否正确 (YYYY-MM-DD)
 */
function isValidDate(dateString) {
    const regex = /^\d{4}-\d{2}-\d{2}$/;
    if (!regex.test(dateString)) return false;
    
    const date = new Date(dateString);
    return date instanceof Date && !isNaN(date);
}

/**
 * 格式化时间段显示
 * @param {number} slot - 时间段编号(0-47)
 * @returns {string} 格式化的时间段字符串
 */
function formatTimeSlot(slot) {
    const hour = Math.floor(slot / 2);
    const minute = (slot % 2) * 30;
    const startHour = hour.toString().padStart(2, '0');
    const startMinute = minute.toString().padStart(2, '0');
    
    const endHour = (minute === 30 ? (hour + 1) : hour).toString().padStart(2, '0');
    const endMinute = (minute === 30 ? '00' : '30');
    
    return `${startHour}:${startMinute}-${endHour}:${endMinute}`;
} 